package com.xxdemo.media;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class AnonymousUploadController {

    private final AnonymousUploadService _uploader;

    public AnonymousUploadController(AnonymousUploadService uploader) {
        this._uploader = uploader;
    }

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Mono<FileUploadResult> upload(@RequestPart("file") FilePart filePart) {
        String origFileName = filePart.filename();
        HttpHeaders headers = filePart.headers();
        MediaType contentType = headers.getContentType();
        if (null == contentType) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }
        Mono<FileUploadChecklist> check = _uploader.uploadFileByFileNameAndContent(origFileName, contentType, filePart.content());
        return check.map((FileUploadChecklist chk) -> FileUploadResult.success("成功: " + chk.getFilePath())
        ).onErrorMap((e) -> {
            String message = e.getMessage();
            System.out.println("上传文件失败: " + origFileName);
            System.out.println(message);
            return new AnonymousUploadControllerError(message, e);
        }).onErrorReturn(FileUploadResult.error("服务器内部错误: " + "未能传送文件“" + origFileName + "”"));
    }
//
//    @GetMapping("foobar")
//    public Mono<String> foobar() {
//        return Mono.just("ok");
//    }
}
